package com.zd.springcloud.provider.tccaction.impl;

import com.zd.springcloud.provider.mapper.GoodMapper;
import com.zd.springcloud.provider.tccaction.GoodAction;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class GoodActionImpl implements GoodAction {


    @Autowired(required = false)
    GoodMapper goodMapper;

    @Override
    public void reduceStock(BusinessActionContext businessActionContext, int num, long goodId) {

        String xid = businessActionContext.getXid();
        //解决幂等问题
        if (goodMapper.existsTryLog(xid) > 0){
            return;
        }

        //解决悬挂问题 没有执行过try 或者 commit就执行 try
        if(goodMapper.existsCommitLog(xid)>0 || goodMapper.existsRollbackLog(xid)>0){
            return;
        }

        goodMapper.reduceStock(num,goodId);

        goodMapper.insertTryLog(xid);
    }

    @Override
    public void commit(BusinessActionContext businessActionContext) {

        String xid = businessActionContext.getXid();
        //解决幂等问题
        if (goodMapper.existsCommitLog(xid) > 0){
            return;
        }
        //解决空提交的问题，一般很少发生
        if(goodMapper.existsTryLog(xid)==0){
            return;
        }

        Integer num = Integer.parseInt(businessActionContext.getActionContext("num").toString());
        Long goodId = Long.parseLong(businessActionContext.getActionContext("goodId").toString());

        goodMapper.reduceCommit(num,goodId);


        //提交成功后添加日志
        goodMapper.insertCommitLog(xid);
    }

    @Override
    public void rollback(BusinessActionContext businessActionContext) {

        String xid = businessActionContext.getXid();

        //解决幂等问题
        if (goodMapper.existsRollbackLog(xid) > 0){
            return;
        }
        //解决空回滚的问题
        if(goodMapper.existsTryLog(xid)==0){
            return;
        }

        Integer num = Integer.parseInt(businessActionContext.getActionContext("num").toString());
        Long goodId = Long.parseLong(businessActionContext.getActionContext("goodId").toString());

        goodMapper.stockRollback(num,goodId);

        goodMapper.insertRollbackLog(xid);

    }
}
